package com.cloudinnov.controller.api;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cloudinnov.aop.SystemLog;
import com.cloudinnov.logic.AlarmUserLogic;
import com.cloudinnov.logic.AlarmWorkOrdersLogic;
import com.cloudinnov.logic.AttachLogic;
import com.cloudinnov.logic.AuthUserLogic;
import com.cloudinnov.logic.EquipmentPointLogic;
import com.cloudinnov.logic.HelpWorkOrderLogic;
import com.cloudinnov.logic.impl.AttachLogicImpl;
import com.cloudinnov.model.AlarmContent;
import com.cloudinnov.model.AlarmWorkOrders;
import com.cloudinnov.model.AlarmWorkUser;
import com.cloudinnov.model.Attach;
import com.cloudinnov.model.AuthUsers;
import com.cloudinnov.model.EquipmentPoints;
import com.cloudinnov.model.HelpWorkOrder;
import com.cloudinnov.model.PageModel;
import com.cloudinnov.model.WorkOrderLogs;
import com.cloudinnov.utils.CommonUtils;
import com.easemob.server.example.comm.body.ImgMessageBody;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.Page;

/**
 * @author chengning
 * @date 2016年2月18日上午10:19:01
 * @email ningcheng@cloudinnov.com
 * @remark
 * @version
 */
@Controller
@RequestMapping("/webapi/alarmWorkOrder")
public class AlarmWorkOrdersController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(AlarmWorkOrdersController.class);
	private final static Integer UPDATE_TYPE_HANGING_YES = 1;
	private final static Integer UPDATE_TYPE_INPUT_YES = 2;// 工单录入
	private final static String SELECTUSER_INVITE_TYPE = "invite"; // 查询客户所属oem下的用户(用于邀请)
	private final static String SELECTUSER_TURN_TYPE = "turn"; // 查询客户下的用户(用于转派)
	@Autowired
	private AlarmWorkOrdersLogic alarmWorkOrdersLogic;
	@Autowired
	private HelpWorkOrderLogic helpWorkOrderLogic;
	@Autowired
	private AttachLogic attachLogic;
	@Autowired
	private AuthUserLogic authUserLogic;
	@Autowired
	private AlarmUserLogic alarmUserLogic;
	@Autowired
	private EquipmentPointLogic equipmentPointLogic;

	@RequestMapping(value = "/launchWorkOrder", method = RequestMethod.POST)
	@ResponseBody
	@SystemLog(module = "工单管理", methods = "发起工单")
	public void launchWorkOrder(HelpWorkOrder helpWorkOrder, HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		helpWorkOrder.setCustomerCode(getUserInfo(request).get(COM_CODE));
		helpWorkOrder.setSponsor(getUserInfo(request).get(USER_CODE));
		int returnCode = helpWorkOrderLogic.save(helpWorkOrder);
		Map<String, Object> map = new HashMap<String, Object>();
		String returnData = null;
		if (returnCode == CommonUtils.SUCCESS_NUM) {
			returnData = returnJsonAllRequest(request, response, map, SUCCESS, null);
		} else {
			returnData = returnJsonAllRequest(request, response, map, ERROR, null);
		}
		response.getWriter().println(returnData);
	}

	@RequestMapping(value = "/helpworksave", method = RequestMethod.POST)
	@ResponseBody
	@SystemLog(module = "工单管理", methods = "发起求助工单")
	public void helpWorkSave(HelpWorkOrder helpWorkOrder, HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		helpWorkOrder.setCustomerCode(getUserInfo(request).get(COM_CODE));
		helpWorkOrder.setSponsor(getUserInfo(request).get(USER_CODE));
		int returnCode = helpWorkOrderLogic.save(helpWorkOrder);
		Map<String, Object> map = new HashMap<String, Object>();
		String returnData = null;
		if (returnCode == CommonUtils.SUCCESS_NUM) {
			returnData = returnJsonAllRequest(request, response, map, SUCCESS, null);
		} else {
			returnData = returnJsonAllRequest(request, response, map, ERROR, null);
		}
		response.getWriter().println(returnData);
	}

	@RequestMapping(value = "/helpworklist")
	@ResponseBody
	public void helpWorkList(int index, int size, HelpWorkOrder helpWorkOrder, HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		helpWorkOrder.setCustomerCode(getUserInfo(request).get(COM_CODE));
		helpWorkOrder.setSponsor(getUserInfo(request).get(USER_CODE));
		Page<HelpWorkOrder> results = helpWorkOrderLogic.selectListPage(index, size, helpWorkOrder, false);
		Map<String, Object> map = new HashMap<String, Object>();
		String returnData = null;
		if (results != null) {
			map.put("list", results);
			returnData = returnJsonAllRequest(request, response, map, SUCCESS, null);
		} else {
			returnData = returnJsonAllRequest(request, response, map, ERROR, null);
		}
		response.getWriter().println(returnData);
	}

	@RequestMapping(value = "/helpworkselect")
	@ResponseBody
	public void helpWorkSelect(HelpWorkOrder helpWorkOrder, HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		if (getUserInfo(request).get(USER_TYPE).equals(CommonUtils.CUSTORER_TYPE)) {
			helpWorkOrder.setCustomerCode(getUserInfo(request).get(COM_CODE));
		}
		helpWorkOrder.setSponsor(getUserInfo(request).get(USER_CODE));
		HelpWorkOrder result = helpWorkOrderLogic.select(helpWorkOrder);
		Map<String, Object> map = new HashMap<String, Object>();
		String returnData = null;
		if (result != null) {
			map.put("model", result);
			returnData = returnJsonAllRequest(request, response, map, SUCCESS, null);
		} else {
			returnData = returnJsonAllRequest(request, response, map, ERROR, null);
		}
		response.getWriter().println(returnData);
	}

	/**
	 * list
	 * 
	 * @Description: 查看工单列表
	 * @param @param
	 *            request
	 * @param @param
	 *            response
	 * @param @param
	 *            model
	 * @param @return
	 * @param @throws
	 *            JsonGenerationException
	 * @param @throws
	 *            JsonMappingException
	 * @param @throws
	 *            IOException 参数
	 * @return
	 * @return String 返回类型
	 */
	@RequestMapping(value = "/list")
	@ResponseBody
	public void list(int index, int size, AlarmWorkOrders alarm, HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		if (getUserInfo(request).get(USER_TYPE).equals(CommonUtils.OEM_TYPE)) {
			alarm.setOemCode(getUserInfo(request).get(OEM_CODE));
		} else if (getUserInfo(request).get(USER_TYPE).equals(CommonUtils.CUSTORER_TYPE)) {
			alarm.setCustomerCode(getUserInfo(request).get(COM_CODE));
		} else if (getUserInfo(request).get(USER_TYPE).equals(CommonUtils.AGENT_TYPE)) {
			alarm.setAgentCode(getUserInfo(request).get(COM_CODE));
		}
		Page<AlarmWorkOrders> alarmWorkOrders = alarmWorkOrdersLogic.selectListPage(index, size, alarm, false);
		if (alarmWorkOrders != null && alarmWorkOrders.size() > DEFAULT_SIZE) {
			Map<String, Object> map = alarmWorkOrdersLogic.selecAllOrderStatus(alarm);
			map.put("laterTime", alarmWorkOrders.get(0).getFirstTime());
			map.put("list", alarmWorkOrders);
			map.put("total", alarmWorkOrders.getTotal());
			String returnData = returnJsonAllRequest(request, response, map, SUCCESS, null);
			response.getWriter().println(returnData);
		} else {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("alarmUntreateds", DEFAULT_NUM);
			map.put("alarmHandles", DEFAULT_NUM);
			map.put("alarmCloses", DEFAULT_NUM);
			map.put("alarmSees", DEFAULT_NUM);
			map.put("laterTime", String.valueOf(System.currentTimeMillis()));
			map.put("list", alarmWorkOrders);
			map.put("total", DEFAULT_NUM);
			String returnData = returnJsonAllRequest(request, response, map, SUCCESS, null);
			response.getWriter().println(returnData);
		}
	}

	@RequestMapping(value = "/searchAlarmAndHelp", method = RequestMethod.POST)
	@ResponseBody
	public void searchALarmAndHelp(PageModel page, String country, String province, String city, String key,
			String orderStatus, String customerCode, String language, String paddingBy, HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		AlarmWorkOrders alarm = new AlarmWorkOrders();
		if (customerCode != null && !customerCode.equals("")) {
			alarm.setCustomerCode(customerCode);
		}
		if (orderStatus != null && !orderStatus.equals("")) {
			alarm.setOrderStatus(Integer.parseInt(orderStatus));
		}
		alarm.setOemCode(getUserInfo(request).get(OEM_CODE));
		alarm.setLanguage(language);
		if (getUserInfo(request).get(USER_TYPE).equals(CommonUtils.CUSTORER_TYPE)) {
			alarm.setCustomerCode(getUserInfo(request).get(COM_CODE));
		} else if (getUserInfo(request).get(USER_TYPE).equals(CommonUtils.AGENT_TYPE)) {
			alarm.setAgentCode(getUserInfo(request).get(COM_CODE));
		}
		Map<String, Object> map = alarmWorkOrdersLogic.searchAlarmAndHelp(page, country, province, city, key, alarm);
		String returnData = returnJsonAllRequest(request, response, map, SUCCESS, "");
		response.getWriter().println(returnData);
	}

	@RequestMapping(value = "/update", method = RequestMethod.POST)
	@ResponseBody
	public void update(AlarmWorkOrders alarm, HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		if (CommonUtils.isEmpty(alarm.getOemCode())) {
			alarm.setOemCode(getUserInfo(request).get(OEM_CODE));
		}
		Map<String, Object> map = new HashMap<String, Object>();
		int returnCode = alarmWorkOrdersLogic.update(alarm);
		if (returnCode == CommonUtils.SUCCESS_NUM) {
			String returnData = returnJsonAllRequest(request, response, map, SUCCESS, "");
			response.getWriter().println(returnData);
		} else {
			String returnData = returnJsonAllRequest(request, response, map, ERROR, "");
			response.getWriter().println(returnData);
		}
	}

	/**
	 * Web工单详情
	 * 
	 * @Title: select
	 * @Description: TODO
	 * @param alarmWorkOrders
	 * @param request
	 * @param response
	 * @throws IOException
	 * @return: void
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/select", method = RequestMethod.GET)
	@ResponseBody
	public void select(AlarmWorkOrders alarmWorkOrders, HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		Map<String, Object> condition = new HashMap<String, Object>();
		condition.put("language", alarmWorkOrders.getLanguage());
		condition.put("code", alarmWorkOrders.getCode());
		Map<String, Object> result = alarmWorkOrdersLogic.selectMap(condition);
		if (result != null && result.size() > DEFAULT_SIZE) {
			String userCode = getUserInfo(request).get(USER_CODE);
			if (userCode != null) {
				if (result.get("customers") != null) {
					List<AuthUsers> users = (List<AuthUsers>) result.get("customers");
					for (AuthUsers user : users) {
						if (user != null && user.getCode().equals(userCode)
								&& (int) result.get("orderStatus") == CommonUtils.ORDER_STATUS_NEW) {
							result.put("isReceiveOrder", CommonUtils.IS_RECEIVE_ORDER_YES);
						} else {
							result.put("isReceiveOrder", CommonUtils.IS_RECEIVE_ORDER_NO);
						}
					}
				}
			}
			/**
			 * 历史故障 一个设备的工单
			 */
			AlarmWorkOrders alarm = new AlarmWorkOrders();
			alarm.setEquipmentCode((String) result.get("equcode"));
			alarm.setLanguage(alarmWorkOrders.getLanguage());
			alarm.setOrderStatus(CommonUtils.ORDER_STATUS_CLOSE);
			List<AlarmWorkOrders> alarmWorkOrdersHistory = alarmWorkOrdersLogic.selectListHistory(alarm);
			/**
			 * 类似故障 故障码相同的工单
			 */
			alarm.setEquipmentCode("");
			alarm.setFaultCode((String) result.get("fcode"));
			alarm.setOrderStatus(CommonUtils.ORDER_STATUS_CLOSE);
			List<AlarmWorkOrders> alarmWorkOrdersLike = alarmWorkOrdersLogic.selectListLike(alarm);
			EquipmentPoints point = new EquipmentPoints();
			point.setLanguage(alarmWorkOrders.getLanguage());
			point.setEquipmentCode((String) result.get("equcode"));
			List<EquipmentPoints> points = equipmentPointLogic.selectList(point, false);
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("alarm", result);
			map.put("alarmHistorys", alarmWorkOrdersHistory);
			map.put("alarmWorkOrdersLikes", alarmWorkOrdersLike);
			map.put("points", points);
			String returnData = returnJsonAllRequest(request, response, map, SUCCESS, null);
			response.getWriter().println(returnData);
		} else {
			Map<String, Object> map = new HashMap<String, Object>();
			String returnData = returnJsonAllRequest(request, response, map, ERROR, null);
			response.getWriter().println(returnData);
		}
	}

	/**
	 * 手机工单详情
	 * 
	 * @Title: moblieSelect
	 * @Description: TODO
	 * @param alarmWorkOrders
	 * @param request
	 * @param response
	 * @throws IOException
	 * @return: void
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/m/select", method = RequestMethod.GET)
	@ResponseBody
	public void moblieSelect(AlarmWorkOrders alarmWorkOrders, HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		Map<String, Object> map = new HashMap<String, Object>();
		Map<String, Object> condition = new HashMap<String, Object>();
		condition.put("language", alarmWorkOrders.getLanguage());
		condition.put("code", alarmWorkOrders.getCode());
		Map<String, Object> result = alarmWorkOrdersLogic.selectMap(condition);
		if (result != null && result.size() > DEFAULT_SIZE) {
			String userCode = getUserInfo(request).get(USER_CODE);
			if (userCode != null) {
				if (result.get("customers") != null) {
					List<AuthUsers> users = (List<AuthUsers>) result.get("customers");
					result.put("canInvatation", CommonUtils.IS_INVATATION_ORDER_NO);
					result.put("canCancle", CommonUtils.IS_CANCLE_ORDER_NO);
					result.put("canTurn", CommonUtils.IS_TURN_ORDER_NO);
					for (AuthUsers user : users) {
						// 当前登陆人包含在设备负责人中,包含即可邀请
						if (user.getCode().equals(userCode)) {
							if ((int) result.get("orderStatus") == CommonUtils.ORDER_STATUS_NEW) {
								result.put("canInvatation", CommonUtils.IS_INVATATION_ORDER_YES);
							} else if ((int) result.get("orderStatus") == CommonUtils.ORDER_STATUS_HANDLE
									&& userCode.equals(result.get("padding_by"))) {
								result.put("canInvatation", CommonUtils.IS_INVATATION_ORDER_YES);
								result.put("canCancle", CommonUtils.IS_CANCLE_ORDER_YES);
								result.put("canTurn", CommonUtils.IS_TURN_ORDER_YES);
							}
							break;
						}
					}
				}
			}
			map.put("model", result);
			String returnData = returnJsonAllRequest(request, response, map, SUCCESS, null);
			response.getWriter().println(returnData);
		} else {
			String returnData = returnJsonAllRequest(request, response, map, ERROR, null);
			response.getWriter().println(returnData);
		}
	}

	@RequestMapping(value = "/m/selectWorkLog")
	@ResponseBody
	public void moblieSelectLog(PageModel page, AlarmWorkOrders alarmWorkOrders, WorkOrderLogs work,
			HttpServletRequest request, HttpServletResponse response) throws IOException {

		Map<String, Object> map = new HashMap<String, Object>();
		Map<String, Object> condition = new HashMap<String, Object>();
		condition.put("language", alarmWorkOrders.getLanguage());
		condition.put("code", alarmWorkOrders.getCode());
		List<WorkOrderLogs> list = alarmWorkOrdersLogic.selectWorkOrderLogsList(page, work);
		// 查询工单处理日志最后记录
		WorkOrderLogs workLog = new WorkOrderLogs();
		workLog.setContent(String.valueOf(map.get("name")) + map.get("handing_suggestion") + map.get("description"));
		workLog.setMsgType(CommonUtils.MSG_TEXT_TYPE);
		list.add(workLog);
		List<AlarmContent> logs = new ArrayList<AlarmContent>();
		for (WorkOrderLogs log : list) {
			AlarmContent content = new AlarmContent();
			if (log.getTargetUser() != null && log.getTargetUser().equals(getUserInfo(request).get(USER_CODE))) {
				content.setCanAnswer(1);
			} else {
				content.setCanAnswer(0);
			}
			content.setMsgType(log.getType());
			content.setSendBy(log.getTargetUser());
			AlarmContent.Message msg = new AlarmContent().new Message();
			msg.setContent(log.getContent());
			if (log.getType() == CommonUtils.WORKLOG_TYPE_MSG_TEXT) {
				msg.setContent(log.getContent());
			} else {
				Attach attach = new Attach();
				attach.setType(AttachLogicImpl.ATTACH_WORKORDER_TYPE);
				attach.setObjectId(log.getId());
				attach = attachLogic.select(attach);
				msg.setContent(log.getContent());
				msg.setUrl(attach.getUrl());
				msg.setPic("");
				msg.setLength(Integer.parseInt(attach.getSize()));
			}
			content.setMessage(msg);
			logs.add(content);
		}
		AlarmContent message = new AlarmContent();
		message.setMsgType(CommonUtils.MSG_TEXT_TYPE);
		// message.Message
		if (list != null && list.size() > DEFAULT_SIZE) {
			map.put("list", list);
			String returnData = returnJsonAllRequest(request, response, map, SUCCESS, null);
			response.getWriter().println(returnData);
		} else {
			map = new HashMap<String, Object>();
			String returnData = returnJsonAllRequest(request, response, map, ERROR, null);
			response.getWriter().println(returnData);
		}
	}

	/**
	 * 工单处理 handleWorkOrder
	 * 
	 * @Description: TODO(这里用一句话描述这个方法的作用)
	 * @param @param
	 *            workOrderLogs
	 * @param @param
	 *            attach
	 * @param @param
	 *            request
	 * @param @param
	 *            response
	 * @param @throws
	 *            IOException 参数
	 * @return void 返回类型
	 */
	@RequestMapping(value = "/handle", method = RequestMethod.POST)
	@ResponseBody
	@SystemLog(module = "工单管理", methods = "工单处理")
	public void handleWorkOrder(WorkOrderLogs workOrderLogs, AlarmWorkOrders alarmWorkOrders,
			HttpServletRequest request, HttpServletResponse response) throws IOException {
		String returnData = null;
		Map<String, Object> map = new HashMap<String, Object>();
		if (getUserInfo(request).get(USER_TYPE).equals(CommonUtils.CUSTORER_TYPE)) {
			workOrderLogs.setCustomerCode(getUserInfo(request).get(COM_CODE));
		}
		workOrderLogs.setUserCode(getUserInfo(request).get(USER_CODE));
		int returnCode = alarmWorkOrdersLogic.saveWorkOrderLogs(workOrderLogs); // 插入工单记录
		if (workOrderLogs.getImagesJson() != null && !workOrderLogs.getImagesJson().equals("")) {
			ObjectMapper mapper = new ObjectMapper();
			String[] urls = mapper.readValue(workOrderLogs.getImagesJson(), String[].class);
			Attach attach = new Attach();
			attach.setObjectId(workOrderLogs.getId()); // 保存图片
			for (int i = 0; i < urls.length; i++) {
				urls[i] = storeBase64(urls[i], request);
			}
			attach.setUrls(urls);
			attachLogic.saveWorderOrderImage(attach);
			if (getUserInfo(request).get(LOGIN_TYPE).equals(CommonUtils.LOGIN_TYPE_APP)) {
				Map<String, Object> webSocketContent = new HashMap<>();
				webSocketContent.put("msgType", CommonUtils.UPLOAD_TYPE_MSG_IMAGE);
				webSocketContent.put("urls", urls);
				AuthUsers user = new AuthUsers();
				user.setCode(getUserInfo(request).get(USER_CODE));
				user.setName(getUserInfo(request).get(USER_NAME));
				user.setLogo(getUserInfo(request).get(USER_LOGO));
				webSocketContent.put("user", user);
				webSocketContent.put("submitTime", System.currentTimeMillis());
				alarmWorkOrdersLogic.sendMesssageToDialogueWebSocket(mapper.writeValueAsString(webSocketContent));// 推送内容
			}
		}
		alarmWorkOrders.setCode(workOrderLogs.getWorkOrderCode());
		// type为 1 解决工单
		if (workOrderLogs.getOperation() == UPDATE_TYPE_HANGING_YES) {
			alarmWorkOrders.setOrderStatus(CommonUtils.ORDER_STATUS_CLOSE);
			alarmWorkOrders.setPaddingBy(getUserInfo(request).get(USER_CODE));
			// type为 2 未解决工单（提供意见）
		}
		returnCode = alarmWorkOrdersLogic.update(alarmWorkOrders);
		if (getUserInfo(request).get(LOGIN_TYPE).equals(CommonUtils.LOGIN_TYPE_APP)) {
			ObjectMapper mapper = new ObjectMapper();
			Map<String, Object> webSocketContent = new HashMap<>();
			webSocketContent.put("msgType", CommonUtils.UPLOAD_TYPE_MSG_TEXT);
			webSocketContent.put("content", workOrderLogs.getContent());
			AuthUsers user = new AuthUsers();
			user.setCode(getUserInfo(request).get(USER_CODE));
			user.setName(getUserInfo(request).get(USER_NAME));
			user.setLogo(getUserInfo(request).get(USER_LOGO));
			webSocketContent.put("user", user);
			webSocketContent.put("submitTime", System.currentTimeMillis());
			alarmWorkOrdersLogic.sendMesssageToDialogueWebSocket(mapper.writeValueAsString(webSocketContent));// 推送内容
		}
		if (returnCode == CommonUtils.SUCCESS_NUM) {
			returnData = returnJsonAllRequest(request, response, map, SUCCESS, "");
		} else {
			returnData = returnJsonAllRequest(request, response, map, ERROR, "");
		}
		response.getWriter().println(returnData);
	}

	/**
	 * 工单转派 turnSendWorkOrder
	 * 
	 * @Description: TODO(这里用一句话描述这个方法的作用)
	 * @param @param
	 *            workOrderLogs
	 * @param @param
	 *            attach
	 * @param @param
	 *            request
	 * @param @param
	 *            response
	 * @param @throws
	 *            IOException 参数
	 * @return void 返回类型
	 */
	@RequestMapping(value = "/turnsend", method = RequestMethod.POST)
	@ResponseBody
	@SystemLog(module = "工单管理", methods = "工单转派")
	public void turnSendWorkOrder(WorkOrderLogs workOrderLogs, AlarmWorkOrders alarmWorkOrders,
			HttpServletRequest request, HttpServletResponse response) throws IOException {
		if (getUserInfo(request).get(USER_TYPE).equals(CommonUtils.CUSTORER_TYPE)) {
			workOrderLogs.setCustomerCode(getUserInfo(request).get(COM_CODE));
		}
		String returnData = null;
		workOrderLogs.setUserCode(getUserInfo(request).get(USER_CODE));
		alarmWorkOrders.setPaddingBy(workOrderLogs.getTargetUser());
		int returnCode = alarmWorkOrdersLogic.saveWorkOrderLogs(workOrderLogs); // 插入工单记录
		if (workOrderLogs.getImagesJson() != null && !workOrderLogs.getImagesJson().equals("")) {
			ObjectMapper mapper = new ObjectMapper();
			String[] urls = mapper.readValue(workOrderLogs.getImagesJson(), String[].class);
			Attach attach = new Attach();
			attach.setObjectId(workOrderLogs.getId()); // 保存图片
			for (int i = 0; i < urls.length; i++) {
				urls[i] = storeBase64(urls[i], request);
			}
			attach.setUrls(urls);
			returnCode = attachLogic.saveWorderOrderImage(attach);
			if (getUserInfo(request).get(LOGIN_TYPE).equals(CommonUtils.LOGIN_TYPE_APP)) {
				Map<String, Object> webSocketContent = new HashMap<>();
				webSocketContent.put("msgType", CommonUtils.UPLOAD_TYPE_MSG_IMAGE);
				webSocketContent.put("urls", urls);
				AuthUsers user = new AuthUsers();
				user.setCode(getUserInfo(request).get(USER_CODE));
				user.setName(getUserInfo(request).get(USER_NAME));
				user.setLogo(getUserInfo(request).get(USER_LOGO));
				webSocketContent.put("user", user);
				webSocketContent.put("submitTime", System.currentTimeMillis());
				alarmWorkOrdersLogic.sendMesssageToDialogueWebSocket(mapper.writeValueAsString(webSocketContent));// 推送内容
			}
		}
		// 图片上传 用于安卓
		String[] fileUrls = uploadFile(request, CommonUtils.UPLOAD_TYPE_MSG_IMAGE_STR);
		Attach attach = new Attach();
		attach.setFileType(CommonUtils.UPLOAD_TYPE_MSG_IMAGE_STR);
		attach.setUrls(fileUrls);
		attach.setObjectId(workOrderLogs.getId()); // 保存图片
		returnCode = attachLogic.saveWorderOrderImage(attach);

		alarmWorkOrders.setCode(workOrderLogs.getWorkOrderCode());
		returnCode = alarmWorkOrdersLogic.update(alarmWorkOrders);
		if (getUserInfo(request).get(LOGIN_TYPE).equals(CommonUtils.LOGIN_TYPE_APP)) {
			ObjectMapper mapper = new ObjectMapper();
			Map<String, Object> webSocketContent = new HashMap<>();
			webSocketContent.put("msgType", CommonUtils.UPLOAD_TYPE_MSG_TEXT);
			webSocketContent.put("content", workOrderLogs.getContent());
			AuthUsers user = new AuthUsers();
			user.setCode(getUserInfo(request).get(USER_CODE));
			user.setName(getUserInfo(request).get(USER_NAME));
			user.setLogo(getUserInfo(request).get(USER_LOGO));
			webSocketContent.put("user", user);
			webSocketContent.put("submitTime", System.currentTimeMillis());
			alarmWorkOrdersLogic.sendMesssageToDialogueWebSocket(mapper.writeValueAsString(webSocketContent));// 推送内容
		}
		Map<String, Object> map = new HashMap<String, Object>();
		if (returnCode == CommonUtils.SUCCESS_NUM) {
			returnData = returnJsonAllRequest(request, response, map, SUCCESS, "");
		} else {
			returnData = returnJsonAllRequest(request, response, map, ERROR, "");
		}
		response.getWriter().println(returnData);
	}

	/**
	 * 工单录入 inputWorkOrder
	 * 
	 * @Description: TODO(这里用一句话描述这个方法的作用)
	 * @param @param
	 *            workOrderLogs
	 * @param @param
	 *            attach
	 * @param @param
	 *            request
	 * @param @param
	 *            response
	 * @param @throws
	 *            IOException 参数j
	 * @return void 返回类型
	 */
	@RequestMapping(value = "/inputAlarmWorkOrder", method = RequestMethod.POST)
	@ResponseBody
	@SystemLog(module = "工单管理", methods = "工单录入")
	public void inputWorkOrder(WorkOrderLogs workOrderLogs, AlarmWorkOrders alarmWorkOrders, HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		String returnData = null;
		Map<String, Object> map = new HashMap<String, Object>();
		if (workOrderLogs.getType() != null && workOrderLogs.getType() == UPDATE_TYPE_INPUT_YES) {
			workOrderLogs.setType(CommonUtils.UPLOAD_TYPE_MSG_TEXT);
			if (getUserInfo(request).get(USER_TYPE).equals(CommonUtils.CUSTORER_TYPE)) {
				workOrderLogs.setCustomerCode(getUserInfo(request).get(COM_CODE));
			} else {
				workOrderLogs.setCustomerCode(getUserInfo(request).get(OEM_CODE));
			}
			workOrderLogs.setOperation(CommonUtils.OPERATION_NOTRESOLVER);
			workOrderLogs.setUserCode(getUserInfo(request).get(USER_CODE));

			alarmWorkOrders.setCode(workOrderLogs.getWorkOrderCode());
			AlarmWorkOrders model = alarmWorkOrdersLogic.select(alarmWorkOrders);
			if (model != null && model.getEmGroupId() != null) {
				String[] targets = new String[] { model.getEmGroupId() };
				// 给此工单的群组发送消息
				Map<String, String> ext = new HashMap<>();
				ext.put("name", getUserInfo(request).get(LOGIN_NAME));
				ext.put("headPhoto", getUserInfo(request).get(USER_LOGO) != null ? getUserInfo(request).get(USER_LOGO)
						: getUserInfo(request).get(DEFAULT_LOGO_USER));
				CommonUtils.sendEmchatMessage(CommonUtils.UPLOAD_TYPE_MSG_TEXT, targets, workOrderLogs.getContent(),
						getUserInfo(request).get(LOGIN_NAME), ext, null);
			}
			if (workOrderLogs.getImagesJson() != null && !workOrderLogs.getImagesJson().equals("[]")) {
				workOrderLogs.setType(CommonUtils.UPLOAD_TYPE_MSG_IMAGE);
			}
			int returnCode = alarmWorkOrdersLogic.saveWorkOrderLogs(workOrderLogs); // 插入工单记录
			if (workOrderLogs.getImagesJson() != null && !workOrderLogs.getImagesJson().equals("[]")) {
				ObjectMapper mapper = new ObjectMapper();
				String[] urls = mapper.readValue(workOrderLogs.getImagesJson(), String[].class);
				Attach attach = new Attach();
				attach.setObjectId(workOrderLogs.getId()); // 保存图片
				ImgMessageBody imgBody;
				for (int i = 0; i < urls.length; i++) {
					urls[i] = storeBase64(urls[i], request);
					if (model != null && model.getEmGroupId() != null) {
						String[] targets = new String[] { model.getEmGroupId() };
						imgBody = new ImgMessageBody("chatgroups", targets, null, null, urls[i], urls[i].split("/")[5],
								CommonUtils.getUUID(), null, null);
						// 给此工单的群组发送消息
						Map<String, String> ext = new HashMap<>();
						ext.put("name", getUserInfo(request).get(LOGIN_NAME));
						ext.put("headPhoto", getUserInfo(request).get(USER_LOGO) != null
								? getUserInfo(request).get(USER_LOGO) : getUserInfo(request).get(DEFAULT_LOGO_USER));
						CommonUtils.sendEmchatMessage(CommonUtils.UPLOAD_TYPE_MSG_IMAGE, targets, null,
								getUserInfo(request).get(LOGIN_NAME), ext, imgBody);
					}
				}
				attach.setUrls(urls);
				attachLogic.saveWorderOrderImage(attach);
			}

			returnCode = alarmWorkOrdersLogic.update(alarmWorkOrders);
			if (returnCode == CommonUtils.SUCCESS_NUM) {
				returnData = returnJsonAllRequest(request, response, map, SUCCESS, "");
			} else {
				returnData = returnJsonAllRequest(request, response, map, ERROR, "");
			}
		} else {
			returnData = returnJsonAllRequest(request, response, CommonUtils.PARAMETER_EXCEPTION_CODE,
					CommonUtils.PARAMETER_EXCEPTION_MSG);
		}
		response.getWriter().println(returnData);
	}

	/**
	 * 工单接单receiveAlarmWorkOrder
	 * 
	 * @Description: TODO(这里用一句话描述这个方法的作用)
	 * @param @param
	 *            workOrderLogs
	 * @param @param
	 *            attach
	 * @param @param
	 *            request
	 * @param @param
	 *            response
	 * @param @throws
	 *            IOException 参数
	 * @return void 返回类型
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/receiveAlarmWorkOrder", method = RequestMethod.POST)
	@ResponseBody
	@SystemLog(module = "工单管理", methods = "工单接单")
	public void receiveAlarmWorkOrder(AlarmWorkOrders alarmWorkOrder, HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		String returnData = null;
		Map<String, Object> condition = new HashMap<String, Object>();
		condition.put("language", alarmWorkOrder.getLanguage());
		condition.put("code", alarmWorkOrder.getCode());
		Map<String, Object> result = alarmWorkOrdersLogic.selectMap(condition);
		if (result != null && result.size() > DEFAULT_SIZE
				&& (int) result.get("orderStatus") == CommonUtils.ORDER_STATUS_NEW) {
			String userCode = getUserInfo(request).get(USER_CODE);
			if (userCode != null) {
				if (result.get("customers") != null) {
					List<AuthUsers> users = (List<AuthUsers>) result.get("customers");
					String[] members = new String[users.size()];
					String[] alias = new String[users.size()];
					for (int i = 0; i < users.size(); i++) {
						members[i] = users.get(i).getLoginName();
						alias[i] = users.get(i).getCode();
					}
					for (int i = 0; i < users.size(); i++) {
						if (users.get(i).getCode().equals(userCode)) {
							alarmWorkOrder.setOrderStatus(CommonUtils.ORDER_STATUS_HANDLE);
							alarmWorkOrder.setPaddingBy(userCode);
							AlarmWorkUser alarmWorkUser = new AlarmWorkUser();
							alarmWorkUser.setCode(alarmWorkOrder.getCode());
							alarmWorkUser.setUserCode(userCode);
							alarmWorkUser.setRole(CommonUtils.ALARM_ROLE_PADDING);
							int returnCode = alarmWorkOrdersLogic.receiveAlarmWorkOrder(alarmWorkUser);
							if (returnCode == CommonUtils.SUCCESS_NUM) {
								// 创建环信群组
								String groupId = CommonUtils.createEmchatGroup(alarmWorkOrder.getCode(),
										alarmWorkOrder.getCode(), 20L, true, users.get(i).getLoginName(), members);
								alarmWorkOrder.setEmGroupId(groupId);
								returnCode = alarmWorkOrdersLogic.update(alarmWorkOrder);// 更新工单状态为处理中
								try {
									// 推送给app透传消息提示刷新页面
									// CommonUtils.sendMessage(alias, "刷新一下",
									// null, "刷新一下", 1);
								} catch (Exception e) {
									logger.error("[method]:receiveAlarmWorkOrder", e);
								}
								WorkOrderLogs workOrderLogs = new WorkOrderLogs();
								workOrderLogs.setWorkOrderCode(alarmWorkOrder.getCode());
								workOrderLogs.setUserCode(getUserInfo(request).get(USER_CODE));
								workOrderLogs.setCustomerCode(getUserInfo(request).get(COM_CODE));
								workOrderLogs.setType(CommonUtils.WORKLOG_TYPE_MSG_TEXT);
								workOrderLogs.setContent(getUserInfo(request).get(USER_NAME) + "接单");
								workOrderLogs.setOperation(CommonUtils.OPERATION_NOTRESOLVER);
								alarmWorkOrdersLogic.saveWorkOrderLogs(workOrderLogs);
								returnData = returnJsonAllRequest(request, response, SUCCESS, CommonUtils.SUCCESS_MSG);
								if (getUserInfo(request).get(LOGIN_TYPE).equals(CommonUtils.LOGIN_TYPE_APP)) {
									ObjectMapper mapper = new ObjectMapper();
									Map<String, Object> webSocketContent = new HashMap<>();
									webSocketContent.put("msgType", CommonUtils.UPLOAD_TYPE_MSG_TEXT);
									webSocketContent.put("content", workOrderLogs.getContent());
									AuthUsers user = new AuthUsers();
									user.setCode(getUserInfo(request).get(USER_CODE));
									user.setName(getUserInfo(request).get(USER_NAME));
									user.setLogo(getUserInfo(request).get(USER_LOGO));
									webSocketContent.put("user", user);
									webSocketContent.put("submitTime", System.currentTimeMillis());
									alarmWorkOrdersLogic.sendMesssageToDialogueWebSocket(
											mapper.writeValueAsString(webSocketContent));// 推送内容
								}
								returnData = returnJsonAllRequest(request, response, SUCCESS, CommonUtils.SUCCESS_MSG);
								break;
							} else {
								returnData = returnJsonAllRequest(request, response, ERROR, CommonUtils.ERROR_MSG);
							}
						} else {
							returnData = returnJsonAllRequest(request, response, ERROR, CommonUtils.ERROR_MSG);
						}
					}
				}
			} else {
				returnData = returnJsonAllRequest(request, response, ERROR, CommonUtils.ERROR_MSG);
			}
		} else {
			returnData = returnJsonAllRequest(request, response, ERROR, CommonUtils.ERROR_MSG);
		}
		response.getWriter().println(returnData);
	}

	@RequestMapping(value = "/selectWorkOrderLog", method = RequestMethod.GET)
	@ResponseBody
	public void select(PageModel page, WorkOrderLogs work, HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		Map<String, Object> map = new HashMap<String, Object>();
		Attach attach = null;
		List<WorkOrderLogs> list = alarmWorkOrdersLogic.selectWorkOrderLogsList(page, work);
		for (WorkOrderLogs log : list) {
			if (log.getTargetUser() != null && log.getTargetUser().equals(getUserInfo(request).get(USER_CODE))) {
				log.setCanAnswer(CommonUtils.IS_RECEIVE_ORDER_YES);// 可接单
			} else {
				log.setCanAnswer(CommonUtils.IS_RECEIVE_ORDER_NO);
			}
			if (log.getType() == CommonUtils.WORKLOG_TYPE_MSG_TEXT) {
				log.setMsgType(CommonUtils.WORKLOG_TYPE_MSG_TEXT);
			} else if (log.getType() == CommonUtils.WORKLOG_TYPE_MSG_IMAGE) {
				log.setMsgType(CommonUtils.WORKLOG_TYPE_MSG_IMAGE);
				attach = new Attach();
				attach.setType(AttachLogicImpl.ATTACH_WORKORDER_TYPE);
				attach.setFileType(CommonUtils.UPLOAD_TYPE_MSG_IMAGE_STR);
				attach.setObjectId(log.getId());
				List<Attach> attachs = attachLogic.selectList(attach, true);
				String[] urls = new String[attachs.size()];
				for (int i = 0; i < attachs.size(); i++) {
					urls[i] = attachs.get(i).getUrl();
				}
				log.setUrls(urls);
			} else if (log.getType() == CommonUtils.WORKLOG_TYPE_MSG_VOICE) {
				log.setMsgType(CommonUtils.WORKLOG_TYPE_MSG_VOICE);
				attach = new Attach();
				attach.setType(AttachLogicImpl.ATTACH_WORKORDER_TYPE);
				attach.setFileType(CommonUtils.UPLOAD_TYPE_MSG_VOICE_STR);
				attach.setObjectId(log.getId());
				List<Attach> attachs = attachLogic.selectList(attach, true);
				String[] urls = new String[attachs.size()];
				for (int i = 0; i < attachs.size(); i++) {
					urls[i] = attachs.get(i).getUrl();
				}
				log.setUrls(urls);
			} else if (log.getType() == CommonUtils.WORKLOG_TYPE_MSG_VIDEO) {
				log.setMsgType(CommonUtils.WORKLOG_TYPE_MSG_VIDEO);
				attach = new Attach();
				attach.setType(AttachLogicImpl.ATTACH_WORKORDER_TYPE);
				attach.setFileType(CommonUtils.UPLOAD_TYPE_MSG_VIDEO_STR);
				attach.setObjectId(log.getId());
				List<Attach> attachs = attachLogic.selectList(attach, true);
				String[] urls = new String[attachs.size()];
				for (int i = 0; i < attachs.size(); i++) {
					urls[i] = attachs.get(i).getUrl();
				}
				log.setUrls(urls);
			}
		}
		if (list != null && list.size() > DEFAULT_SIZE) {
			map.put("list", list);
			String returnData = returnJsonAllRequest(request, response, map, SUCCESS, null);
			response.getWriter().println(returnData);
		} else {
			map = new HashMap<String, Object>();
			String returnData = returnJsonAllRequest(request, response, map, ERROR, null);
			response.getWriter().println(returnData);
		}
	}

	/**
	 * selectEquipmentTotalByCustomerId
	 * 
	 * @Description: 根据客户id 查询该客户下的工单总数
	 * @param @param
	 *            customerCode
	 * @param @param
	 *            request
	 * @param @param
	 *            response
	 * @param @return
	 * @param @throws
	 *            JsonGenerationException
	 * @param @throws
	 *            JsonMappingException
	 * @param @throws
	 *            IOException 参数
	 * @return JSONPObject 返回类型
	 */
	@RequestMapping(value = "/selectWorkOrdersTotalByCustomerId")
	@ResponseBody
	public void selectEquipmentTotalByCustomerId(String customerCode, HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		int result = alarmWorkOrdersLogic.selectWorkOrdersTotalByCustomerCode(customerCode);
		Map<String, Object> map = new HashMap<String, Object>();
		if (result == DEFAULT_SUCCESS_SIZE) {
			String returnData = returnJsonAllRequest(request, response, map, SUCCESS, null);
			response.getWriter().println(returnData);
		} else {
			String returnData = returnJsonAllRequest(request, response, map, ERROR, null);
			response.getWriter().println(returnData);
		}
	}

	@RequestMapping(value = "/search", method = RequestMethod.POST)
	@ResponseBody
	public void search(@Valid PageModel page, String country, String province, String city, String key,
			String orderStatus, String customerCode, String language, String paddingBy, Integer level, Integer type,
			HttpServletRequest request, HttpServletResponse response) throws IOException {
		String oemCode = getUserInfo(request).get(OEM_CODE);
		if (getUserInfo(request).get(USER_TYPE).equals(CommonUtils.ADMIN_TYPE)) {
			oemCode = "";
			customerCode = "";
		} else if (getUserInfo(request).get(USER_TYPE).equals(CommonUtils.CUSTORER_TYPE)) {
			customerCode = getUserInfo(request).get(COM_CODE);
		} else if (getUserInfo(request).get(USER_TYPE).equals(CommonUtils.AGENT_TYPE)) {
			oemCode = getUserInfo(request).get(COM_CODE);
		}
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("oemCode", oemCode);
		params.put("comCode", customerCode);
		params.put("country", country);
		params.put("province", province);
		params.put("city", city);
		params.put("keyword", key);
		params.put("orderstatus", orderStatus);
		params.put("language", language);
		params.put("paddingBy", paddingBy);
		params.put("level", level);
		params.put("type", type);
		Map<String, Object> map = alarmWorkOrdersLogic.search(page, params);
		String returnData = returnJsonAllRequest(request, response, map, SUCCESS, "");
		response.getWriter().println(returnData);
	}

	/**
	 * 代办工单
	 * 
	 * @Title: selectAgencyWorkOrderList
	 * @Description: TODO
	 * @param page
	 * @param country
	 * @param province
	 * @param city
	 * @param key
	 * @param customerCode
	 * @param language
	 * @param paddingBy
	 * @param level
	 * @param type
	 * @param request
	 * @param response
	 * @throws IOException
	 * @return: void
	 */
	@RequestMapping(value = "/agencyWorkOrderList", method = RequestMethod.POST)
	@ResponseBody
	public void selectAgencyWorkOrderList(@Valid PageModel page, String country, String province, String city,
			String key, String customerCode, String language, String paddingBy, Integer level, Integer type,
			HttpServletRequest request, HttpServletResponse response) throws IOException {
		String oemCode = getUserInfo(request).get(OEM_CODE);
		if (getUserInfo(request).get(USER_TYPE).equals(CommonUtils.ADMIN_TYPE)) {
			oemCode = "";
			customerCode = "";
		} else if (getUserInfo(request).get(USER_TYPE).equals(CommonUtils.CUSTORER_TYPE)) {
			customerCode = getUserInfo(request).get(COM_CODE);
		} else if (getUserInfo(request).get(USER_TYPE).equals(CommonUtils.AGENT_TYPE)) {
			oemCode = getUserInfo(request).get(COM_CODE);
		}
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("oemCode", oemCode);
		params.put("comCode", customerCode);
		params.put("country", country);
		params.put("province", province);
		params.put("city", city);
		params.put("keyword", key);
		params.put("orderstatus", CommonUtils.ORDER_STATUS_CLOSE);
		params.put("language", language);
		params.put("paddingBy", paddingBy);
		params.put("level", level);
		params.put("type", type);
		Map<String, Object> map = alarmWorkOrdersLogic.selectAgencyWorkOrderList(page, params);
		String returnData = returnJsonAllRequest(request, response, map, SUCCESS, "");
		response.getWriter().println(returnData);
	}

	/**
	 * 我的工单列表 select
	 * 
	 * @Description: TODO(这里用一句话描述这个方法的作用)
	 * @param @param
	 *            request
	 * @param @param
	 *            response
	 * @param @param
	 *            model
	 * @param @throws
	 *            IOException 参数
	 * @return void 返回类型
	 */
	@RequestMapping("/selectmyalarm")
	@ResponseBody
	public void selectMyAlarm(AlarmWorkOrders alarm, int index, int size, HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		Map<String, Object> map = new HashMap<String, Object>();
		alarm.setPaddingBy(getUserInfo(request).get(USER_CODE));
		alarm.setCustomerCode(getUserInfo(request).get(COM_CODE));
		/**
		 * 查询我的工单统计
		 */
		Map<String, Object> alarmMap = alarmWorkOrdersLogic.selecAlarmsByUserCode(alarm);
		map.put("summary", alarmMap);
		/**
		 * 查询我的工单列表
		 */
		Page<AlarmWorkOrders> alarms = alarmWorkOrdersLogic.selectAlarmWorksByUser(alarm, index, size);
		if (alarms != null && alarms.size() > 0) {
			map.put("list", alarms);
			map.put("total", alarms.getTotal());
			String returnData = returnJsonAllRequest(request, response, map, SUCCESS, "");
			response.getWriter().println(returnData);
		} else {
			String returnData = returnJsonAllRequest(request, response, map, SUCCESS, "");
			response.getWriter().println(returnData);
		}
	}

	@RequestMapping("/selectcustomeralarm")
	@ResponseBody
	public void selectCustomerAlarm(AlarmWorkOrders alarm, HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		Map<String, Object> map = new HashMap<String, Object>();
		Map<String, Object> alarms = alarmWorkOrdersLogic.selecAllOrderStatus(alarm);
		if (alarms != null && alarms.size() > 0) {
			map.put("summary", alarms);
			String returnData = returnJsonAllRequest(request, response, map, SUCCESS, "");
			response.getWriter().println(returnData);
		} else {
			String returnData = returnJsonAllRequest(request, response, map, SUCCESS, "");
			response.getWriter().println(returnData);
		}
	}

	@RequestMapping("/selectequipmentalarm")
	@ResponseBody
	public void selectEquipmentAlarm(AlarmWorkOrders alarm, HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		Map<String, Object> map = new HashMap<String, Object>();
		List<AlarmWorkOrders> alarmWorkOrdersHistory = alarmWorkOrdersLogic.selectListHistory(alarm);
		if (alarmWorkOrdersHistory != null && alarmWorkOrdersHistory.size() > 0) {
			map.put("list", alarmWorkOrdersHistory);
			String returnData = returnJsonAllRequest(request, response, map, SUCCESS, "");
			response.getWriter().println(returnData);
		} else {
			String returnData = returnJsonAllRequest(request, response, map, SUCCESS, "");
			response.getWriter().println(returnData);
		}
	}

	/**
	 * 获取工单数量统计
	 * 
	 * @Title: getWorkOrderStatusCount
	 * @Description: 获取工单数量统计,3种工单状态数量
	 * @param alarm
	 *            oemcode
	 * @param request
	 * @param response
	 * @throws IOException
	 * @return: void 3种工单状态数量
	 */
	@RequestMapping("/getWorkOrderStatusCount")
	@ResponseBody
	public void getWorkOrderStatusCount(AlarmWorkOrders alarm, HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		if (CommonUtils.isEmpty(alarm.getOemCode())) {
			alarm.setOemCode(getUserInfo(request).get(OEM_CODE));
		}
		Map<String, Object> map = new HashMap<String, Object>();
		Map<String, Object> result = alarmWorkOrdersLogic.selecAllOrderStatus(alarm);
		if (result != null) {
			map.put("model", result);
			String returnData = returnJsonAllRequest(request, response, map, SUCCESS, "");
			response.getWriter().println(returnData);
		} else {
			String returnData = returnJsonAllRequest(request, response, map, ERROR, "");
			response.getWriter().println(returnData);
		}
	}

	/**
	 * 获取一段时间设备故障占比
	 * 
	 * @Title: 获取一段时间设备故障占比
	 * @Description: TODO
	 * @param alarm
	 * @param startTime
	 * @param endTime
	 * @param request
	 * @param response
	 * @throws IOException
	 * @return: void 返回一段时间内设备故障数量
	 */
	@RequestMapping("/getEquipmentFaultProportion")
	@ResponseBody
	public void getEquipmentFaultProportion(AlarmWorkOrders alarm, long startTime, long endTime,
			HttpServletRequest request, HttpServletResponse response) throws IOException {
		if (CommonUtils.isEmpty(alarm.getOemCode())) {
			alarm.setOemCode(getUserInfo(request).get(OEM_CODE));
		}
		Map<String, Object> map = new HashMap<String, Object>();
		List<AlarmWorkOrders> list = alarmWorkOrdersLogic.selectEquipmentFaultProportion(alarm, startTime, endTime);
		if (list != null && list.size() > 0) {
			map.put("list", list);
			String returnData = returnJsonAllRequest(request, response, map, SUCCESS, "");
			response.getWriter().println(returnData);
		} else {
			String returnData = returnJsonAllRequest(request, response, map, ERROR, "");
			response.getWriter().println(returnData);
		}
	}

	@RequestMapping("/getFaultListByState")
	@ResponseBody
	public void getFaultListByState(AlarmWorkOrders alarm, HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		if (CommonUtils.isEmpty(alarm.getOemCode())) {
			alarm.setOemCode(getUserInfo(request).get(OEM_CODE));
		}
		Map<String, Object> map = new HashMap<String, Object>();
		List<AlarmWorkOrders> list = alarmWorkOrdersLogic.selectListWhere(alarm);
		if (list != null && list.size() > 0) {
			map.put("list", list);
			String returnData = returnJsonAllRequest(request, response, map, SUCCESS, "");
			response.getWriter().println(returnData);
		} else {
			String returnData = returnJsonAllRequest(request, response, map, ERROR, "");
			response.getWriter().println(returnData);
		}
	}

	/**
	 * 手机工单对话
	 * 
	 * @Title: workOrderDialogue
	 * @Description: TODO
	 * @param workOrderLogs
	 * @param request
	 * @param response
	 * @throws IllegalStateException
	 * @throws IOException
	 * @return: void
	 */
	@RequestMapping(value = "/m/handleDialogue", method = RequestMethod.POST)
	public void workOrderDialogue(WorkOrderLogs workOrderLogs, HttpServletRequest request, HttpServletResponse response)
			throws IllegalStateException, IOException {
		if (getUserInfo(request).get(USER_TYPE).equals(CommonUtils.CUSTORER_TYPE)) {
			workOrderLogs.setCustomerCode(getUserInfo(request).get(COM_CODE));
		}
		if (workOrderLogs.getCustomerCode() == null) {
			String returnData = returnJsonAllRequest(request, response, CommonUtils.PARAMETER_EXCEPTION_CODE,
					CommonUtils.PARAMETER_EXCEPTION_MSG);
			response.getWriter().println(returnData);
			return;
		}
		Map<String, Object> map = new HashMap<String, Object>();
		int msgType = Integer.parseInt(request.getParameter("msgType"));
		String alarmCode = request.getParameter("code");
		int returnCode = 0;
		ObjectMapper mapper = new ObjectMapper();
		if (msgType == CommonUtils.UPLOAD_TYPE_MSG_TEXT) {
			String content = request.getParameter("content");
			workOrderLogs.setUserCode(getUserInfo(request).get(USER_CODE));
			workOrderLogs.setWorkOrderCode(alarmCode);
			workOrderLogs.setType(CommonUtils.WORKLOG_TYPE_MSG_TEXT);
			workOrderLogs.setContent(content);
			workOrderLogs.setOperation(CommonUtils.OPERATION_NOTRESOLVER);
			returnCode = alarmWorkOrdersLogic.saveWorkOrderLogs(workOrderLogs); // 插入工单记录
			Map<String, Object> webSocketContent = new HashMap<>();
			webSocketContent.put("msgType", CommonUtils.UPLOAD_TYPE_MSG_TEXT);
			webSocketContent.put("content", content);
			AuthUsers user = new AuthUsers();
			user.setCode(getUserInfo(request).get(USER_CODE));
			user.setName(getUserInfo(request).get(USER_NAME));
			user.setLogo(getUserInfo(request).get(USER_LOGO));
			webSocketContent.put("user", user);
			webSocketContent.put("submitTime", System.currentTimeMillis());
			alarmWorkOrdersLogic.sendMesssageToDialogueWebSocket(mapper.writeValueAsString(webSocketContent));// 推送内容
		} else if (msgType == CommonUtils.UPLOAD_TYPE_MSG_IMAGE) {
			String[] fileUrls = uploadFile(request, CommonUtils.UPLOAD_TYPE_MSG_IMAGE_STR);
			Attach attach = new Attach();
			attach.setFileType(CommonUtils.UPLOAD_TYPE_MSG_IMAGE_STR);
			attach.setUrls(fileUrls);
			workOrderLogs.setUserCode(getUserInfo(request).get(USER_CODE));
			workOrderLogs.setWorkOrderCode(alarmCode);
			workOrderLogs.setType(CommonUtils.WORKLOG_TYPE_MSG_IMAGE);
			workOrderLogs.setContent("图片");
			workOrderLogs.setOperation(CommonUtils.OPERATION_NOTRESOLVER);
			returnCode = alarmWorkOrdersLogic.saveWorkOrderLogs(workOrderLogs); // 插入工单记录
			attach.setObjectId(workOrderLogs.getId()); // 保存图片
			returnCode = attachLogic.saveWorderOrderImage(attach);
			Map<String, Object> webSocketContent = new HashMap<>();
			webSocketContent.put("msgType", CommonUtils.UPLOAD_TYPE_MSG_IMAGE);
			webSocketContent.put("urls", fileUrls);
			AuthUsers user = new AuthUsers();
			user.setCode(getUserInfo(request).get(USER_CODE));
			user.setName(getUserInfo(request).get(USER_NAME));
			user.setLogo(getUserInfo(request).get(USER_LOGO));
			webSocketContent.put("user", user);
			webSocketContent.put("submitTime", System.currentTimeMillis());
			alarmWorkOrdersLogic.sendMesssageToDialogueWebSocket(mapper.writeValueAsString(webSocketContent));// 推送路径
		} else if (msgType == CommonUtils.UPLOAD_TYPE_MSG_VOICE) {
			String[] fileUrls = uploadFile(request, CommonUtils.UPLOAD_TYPE_MSG_VOICE_STR);
			Attach attach = new Attach();
			attach.setFileType(CommonUtils.UPLOAD_TYPE_MSG_VOICE_STR);
			attach.setUrls(fileUrls);
			workOrderLogs.setUserCode(getUserInfo(request).get(USER_CODE));
			workOrderLogs.setWorkOrderCode(alarmCode);
			workOrderLogs.setType(CommonUtils.WORKLOG_TYPE_MSG_VOICE);
			workOrderLogs.setContent("声音");
			workOrderLogs.setOperation(CommonUtils.OPERATION_NOTRESOLVER);
			returnCode = alarmWorkOrdersLogic.saveWorkOrderLogs(workOrderLogs); // 插入工单记录
			attach.setObjectId(workOrderLogs.getId()); // 保存声音
			returnCode = attachLogic.saveWorderOrderImage(attach);
			Map<String, Object> webSocketContent = new HashMap<>();
			webSocketContent.put("msgType", CommonUtils.UPLOAD_TYPE_MSG_VOICE);
			webSocketContent.put("urls", fileUrls);
			AuthUsers user = new AuthUsers();
			user.setCode(getUserInfo(request).get(USER_CODE));
			user.setName(getUserInfo(request).get(USER_NAME));
			user.setLogo(getUserInfo(request).get(USER_LOGO));
			webSocketContent.put("user", user);
			webSocketContent.put("submitTime", System.currentTimeMillis());
			alarmWorkOrdersLogic.sendMesssageToDialogueWebSocket(mapper.writeValueAsString(webSocketContent));// 推送路径
		} else if (msgType == CommonUtils.UPLOAD_TYPE_MSG_VIDEO) {
			String[] fileUrls = uploadFile(request, CommonUtils.UPLOAD_TYPE_MSG_VIDEO_STR);
			Attach attach = new Attach();
			attach.setFileType(CommonUtils.UPLOAD_TYPE_MSG_VIDEO_STR);
			attach.setUrls(fileUrls);
			workOrderLogs.setUserCode(getUserInfo(request).get(USER_CODE));
			workOrderLogs.setWorkOrderCode(alarmCode);
			workOrderLogs.setType(CommonUtils.WORKLOG_TYPE_MSG_VIDEO);
			workOrderLogs.setContent("视频");
			workOrderLogs.setOperation(CommonUtils.OPERATION_NOTRESOLVER);
			returnCode = alarmWorkOrdersLogic.saveWorkOrderLogs(workOrderLogs); // 插入工单记录
			attach.setObjectId(workOrderLogs.getId()); // 保存视频
			returnCode = attachLogic.saveWorderOrderImage(attach);
			Map<String, Object> webSocketContent = new HashMap<>();
			webSocketContent.put("msgType", CommonUtils.UPLOAD_TYPE_MSG_VIDEO);
			webSocketContent.put("urls", fileUrls);
			AuthUsers user = new AuthUsers();
			user.setCode(getUserInfo(request).get(USER_CODE));
			user.setName(getUserInfo(request).get(USER_NAME));
			user.setLogo(getUserInfo(request).get(USER_LOGO));
			webSocketContent.put("user", user);
			webSocketContent.put("submitTime", System.currentTimeMillis());
			alarmWorkOrdersLogic.sendMesssageToDialogueWebSocket(mapper.writeValueAsString(webSocketContent));// 推送路径
		}
		if (returnCode == CommonUtils.SUCCESS_NUM) {
			String returnData = returnJsonAllRequest(request, response, map, SUCCESS, "");
			response.getWriter().println(returnData);
		} else {
			String returnData = returnJsonAllRequest(request, response, map, ERROR, "");
			response.getWriter().println(returnData);
		}
	}

	@RequestMapping(value = "/selectUsers", method = RequestMethod.GET)
	@ResponseBody
	public void selectAuthUserNameAndCode(boolean filter, String type, String alarmCode, AuthUsers user,
			HttpServletRequest request, HttpServletResponse response) throws IOException {
		Map<String, Object> map = new HashMap<String, Object>();
		List<AuthUsers> users = new ArrayList<AuthUsers>();
		List<AlarmWorkUser> alarmUsers = new ArrayList<AlarmWorkUser>();
		if (type.equals(SELECTUSER_INVITE_TYPE)) {
			user.setRoleName(CommonUtils.ROLE_NAME_ENGINEER);
		}
		if (getUserInfo(request).get(USER_TYPE).equals(CommonUtils.OEM_TYPE)) {
			user.setCompanyCode(getUserInfo(request).get(OEM_CODE));
		} else if (getUserInfo(request).get(USER_TYPE).equals(CommonUtils.AGENT_TYPE)) {
			user.setCompanyCode(getUserInfo(request).get(COM_CODE));
		} else if (getUserInfo(request).get(USER_TYPE).equals(CommonUtils.CUSTORER_TYPE)) {
			if (type.equals(SELECTUSER_INVITE_TYPE)) {
				AlarmWorkUser alarmUser = new AlarmWorkUser();
				alarmUser.setCode(alarmCode);
				alarmUsers = alarmUserLogic.selectList(alarmUser, false);
				// 查询oem下的用户
				user.setCompanyCode(getUserInfo(request).get(OEM_CODE));
				user.setRoleName(CommonUtils.ROLE_NAME_ENGINEER);
				List<AuthUsers> list = authUserLogic.selectList(user, false);
				if (list != null && list.size() > 0) {
					users.addAll(list);
				}
				user.setCompanyCode(getUserInfo(request).get(COM_CODE));
			} else if (type.equals(SELECTUSER_TURN_TYPE)) {
				user.setCompanyCode(getUserInfo(request).get(COM_CODE));
			}
		}
		List<AuthUsers> list = authUserLogic.selectList(user, false);
		if (list != null && list.size() > 0) {
			users.addAll(list);
		}
		if (type.equals(SELECTUSER_INVITE_TYPE)) {
			for (AuthUsers u : users) {// 邀请请列表去除工单参与者
				u.setName(u.getName() + CommonUtils.LEFT_BRACKETS + u.getRoleName() + CommonUtils.RIGHT_BRACKETS);
				// 在迭代过程中准备添加或者删除元素
				Iterator<AlarmWorkUser> it = alarmUsers.iterator();
				while (it.hasNext()) {
					AlarmWorkUser alarmUser = (AlarmWorkUser) it.next();
					if (u.getCode().equals(alarmUser.getUserCode())) {
						it.remove();
					}
				}
			}
		}
		if (filter) {
			for (AuthUsers u : users) {
				if (getUserInfo(request).get(USER_CODE).equals(u.getCode())) {
					users.remove(u);
					break;
				}
			}
		}
		if (users != null && users.size() > DEFAULT_SIZE) {
			map.put("users", users);
			String returnData = returnJsonAllRequest(request, response, map, SUCCESS, null);
			response.getWriter().println(returnData);
		} else {
			String returnData = returnJsonAllRequest(request, response, map, ERROR, null);
			response.getWriter().println(returnData);
		}
	}

	@RequestMapping(value = "/invitation", method = RequestMethod.POST)
	@ResponseBody
	@SystemLog(module = "工单管理", methods = "工单邀请")
	public void alarmWorkInvitation(AlarmWorkOrders alarmWorkOrders, HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		Map<String, Object> map = new HashMap<String, Object>();
		String returnData = null;
		int returnCode = 0;
		String invitationUsers = "";
		if (alarmWorkOrders.getPaddingBy() != null) {
			AlarmWorkOrders model = alarmWorkOrdersLogic.select(alarmWorkOrders);
			String[] paddingBy = alarmWorkOrders.getPaddingBy().split(CommonUtils.SPLIT_COMMA);
			for (String userCode : paddingBy) {
				AlarmWorkUser alarmWorkUser = new AlarmWorkUser();
				alarmWorkUser.setCode(alarmWorkOrders.getCode());
				alarmWorkUser.setUserCode(userCode);
				alarmWorkUser.setRole(CommonUtils.ALARM_ROLE_PARTIN);
				returnCode = alarmWorkOrdersLogic.receiveAlarmWorkOrder(alarmWorkUser);
				if (model != null && model.getEmGroupId() != null) {
					AuthUsers user = new AuthUsers();
					user.setCode(userCode);
					user.setLanguage(alarmWorkOrders.getLanguage());
					user = authUserLogic.select(user);
					if (user != null) {
						CommonUtils.addEmchatUserToChatGroup(model.getEmGroupId(), user.getLoginName());// 邀请人加入群组
						invitationUsers += user.getName() + ",";
					} else {
						returnData = returnJsonAllRequest(request, response, CommonUtils.PARAMETER_EXCEPTION_CODE,
								CommonUtils.PARAMETER_EXCEPTION_MSG);
						response.getWriter().println(returnData);
					}
				}
			}
		} else {
			returnData = returnJsonAllRequest(request, response, CommonUtils.PARAMETER_EXCEPTION_CODE,
					CommonUtils.PARAMETER_EXCEPTION_MSG);
		}
		if (returnCode == CommonUtils.SUCCESS_NUM) {
			WorkOrderLogs workOrderLogs = new WorkOrderLogs();
			workOrderLogs.setWorkOrderCode(alarmWorkOrders.getCode());
			workOrderLogs.setUserCode(getUserInfo(request).get(USER_CODE));
			workOrderLogs.setCustomerCode(getUserInfo(request).get(COM_CODE));
			workOrderLogs.setType(CommonUtils.WORKLOG_TYPE_MSG_TEXT);
			workOrderLogs.setContent(getUserInfo(request).get(USER_NAME) + "邀请了" + invitationUsers);
			workOrderLogs.setOperation(CommonUtils.OPERATION_NOTRESOLVER);
			alarmWorkOrdersLogic.saveWorkOrderLogs(workOrderLogs);
			if (getUserInfo(request).get(LOGIN_TYPE).equals(CommonUtils.LOGIN_TYPE_APP)) {
				ObjectMapper mapper = new ObjectMapper();
				Map<String, Object> webSocketContent = new HashMap<>();
				webSocketContent.put("msgType", CommonUtils.UPLOAD_TYPE_MSG_TEXT);
				webSocketContent.put("content", workOrderLogs.getContent());
				AuthUsers user = new AuthUsers();
				user.setCode(getUserInfo(request).get(USER_CODE));
				user.setName(getUserInfo(request).get(USER_NAME));
				user.setLogo(getUserInfo(request).get(USER_LOGO));
				webSocketContent.put("user", user);
				webSocketContent.put("submitTime", System.currentTimeMillis());
				alarmWorkOrdersLogic.sendMesssageToDialogueWebSocket(mapper.writeValueAsString(webSocketContent));// 推送内容
			}
			returnData = returnJsonAllRequest(request, response, map, SUCCESS, "");
		} else {
			returnData = returnJsonAllRequest(request, response, map, ERROR, "");
		}
		response.getWriter().println(returnData);
	}
	
	/**
	 * 根据设备分类code查询故障工单
	 * selectFaultWorkOrderByEquipmenstCode
	 * @Description
	 * @param
	 * @return
	 */
	@RequestMapping(value="/selectFaultWorkOrderByEquCode" ,method = RequestMethod.GET)
	@ResponseBody
	@SystemLog(module="故障工单管理",methods="根据设备分类code查询故障工单")
	public void selectFaultWorkOrderByEquipmenstCode(String categoryCode,HttpServletRequest request,
			HttpServletResponse response) throws IOException{
		
		List<AlarmWorkOrders> workOrderNInfo = alarmWorkOrdersLogic.selectUntreatedWorkOrder(categoryCode,null);
		
		List<AlarmWorkOrders> workOrderYInfo = alarmWorkOrdersLogic.selectUntreatedWorkOrder(categoryCode,2);
		
		HashMap<String, Object> map = new HashMap<String,Object>();
		
		map.put("unDis", workOrderNInfo.size());
		map.put("dis", workOrderYInfo.size());
		
		String returnData = "";
		
		if(workOrderNInfo.size() != 0 && workOrderYInfo.size() != 0){
			
			map.put("unDisWorkOrder", workOrderNInfo);
			map.put("disWorkOrder", workOrderYInfo);
			
			returnData = returnJsonAllRequest(request, response, map, SUCCESS,"");
		}else{
			returnData = returnJsonAllRequest(request, response, map, ERROR,"");
		}
		response.getWriter().print(returnData);
	}
	
}
